//
//  DownloadCell.m
//  51-Tour
//
//  Created by xiang ying on 14-3-27.
//  Copyright (c) 2014年 xiang ying. All rights reserved.
//

#import "DownloadCell.h"
#import "NSString+TPCategory.h"
#import "DownloadManagement.h"

@interface DownloadCell(){
 
    UILabel *_nameLabel;
    UILabel *_sizeLabel;
    UIProgressView      *_progressView;
    UILabel             *_progressLabel;
    UIButton            *_downloadBtn;
    UIButton            *_cancelBtn;
    ScenicScene     *_scenic;
}
@end

@implementation DownloadCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, 80, 21)];
        _nameLabel.font = [UIFont systemFontOfSize:14];
        _nameLabel.text = @"明孝陵";
        _nameLabel.backgroundColor = [UIColor clearColor];
        [self addSubview:_nameLabel];
        
        _sizeLabel = [[UILabel alloc] initWithFrame:CGRectMake(10+80, _nameLabel.frame.origin.y, 80, _nameLabel.frame.size.height)];
        _sizeLabel.font = [UIFont systemFontOfSize:12];
        _sizeLabel.textColor = THEMECOLOR;
        _sizeLabel.backgroundColor = [UIColor clearColor];
        _sizeLabel.text = @"(10M)";
        [self addSubview:_sizeLabel];
        
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(10, DownloadCellHeight/2-5, 300, 5)];
        [self addSubview:_progressView];
        
        _progressLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, DownloadCellHeight-26-10, 120, 26)];
        _progressLabel.textColor = THEMECOLOR;
        _progressLabel.font = [UIFont systemFontOfSize:13];
        _progressLabel.text = @"正在下载 80%";
        _progressLabel.backgroundColor = [UIColor clearColor];
        [self addSubview:_progressLabel];
        
        
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelBtn.frame = CGRectMake(320-80-5, _progressLabel.frame.origin.y, 80, _progressLabel.frame.size.height);
        [_cancelBtn setTitleColor:THEMECOLOR forState:UIControlStateNormal];
        _cancelBtn.layer.borderWidth = 1;
        _cancelBtn.layer.borderColor = THEMECOLOR.CGColor;
        _cancelBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_cancelBtn setTitle:[[DataCenter instance] getStringForKey:@"delete"] forState:UIControlStateNormal];
        [_cancelBtn addTarget:self action:@selector(cancelDownload:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_cancelBtn];
        
        _downloadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _downloadBtn.frame = CGRectMake(_cancelBtn.frame.origin.x-_cancelBtn.frame.size.width-20, _cancelBtn.frame.origin.y, _cancelBtn.frame.size.width, _cancelBtn.frame.size.height);
        [_downloadBtn setTitleColor:THEMECOLOR forState:UIControlStateNormal];
        _downloadBtn.layer.borderWidth = 1;
        _downloadBtn.layer.borderColor = THEMECOLOR.CGColor;
        [_downloadBtn setTitle:@"暂停" forState:UIControlStateNormal];
        _downloadBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [_downloadBtn addTarget:self action:@selector(download:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_downloadBtn];
        
        UIImageView *_line = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"list-line_14"]];
        _line.frame = CGRectMake(0, DownloadCellHeight-1, 320, 1);
        [self addSubview:_line];
    }
    return self;
}

- (void)awakeFromNib
{
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}


-(void)updateWithData:(ScenicScene*)data{
    _scenic = data;
    
    @try {
        [_scenic removeObserver:self forKeyPath:@"progress"];
        [_scenic removeObserver:self forKeyPath:@"isDownloading"];
    }
    @catch (NSException *exception) {
        
    }
    @finally {
        
    }
    
    [_cancelBtn setTitle:[[DataCenter instance] getStringForKey:@"delete"] forState:UIControlStateNormal];

    if (_scenic.needUpdate) {
        [_scenic addObserver:self forKeyPath:@"progress" options:NSKeyValueObservingOptionNew context:nil];
        [_scenic addObserver:self forKeyPath:@"isDownloading" options:NSKeyValueObservingOptionNew context:nil];
        [self setDowloadSate:4];
    }else if (_scenic.progress != _scenic.zipSize) {
        [_scenic addObserver:self forKeyPath:@"progress" options:NSKeyValueObservingOptionNew context:nil];
        [_scenic addObserver:self forKeyPath:@"isDownloading" options:NSKeyValueObservingOptionNew context:nil];
        if (_scenic.isDownloading) {
            [self setDowloadSate:2];
        }else{
            [self setDowloadSate:3];
        }
    }else{
        //下完了
        [self setDowloadSate:1];
    }

    _nameLabel.text = data.scenicName;
    [_nameLabel setFrame:CGRectMake(_nameLabel.frame.origin.x, _nameLabel.frame.origin.y, [data.scenicName widthwithfont:_nameLabel.font height:_nameLabel.frame.size.height], _nameLabel.frame.size.height)];
    _sizeLabel.text = [NSString stringWithFormat:@"(%.2fMB)",data.zipSize/1024/1024];
    _sizeLabel.frame = CGRectMake(_nameLabel.frame.origin.x+_nameLabel.frame.size.width+5, _sizeLabel.frame.origin.y, _sizeLabel.frame.size.width, _sizeLabel.frame.size.height);
    [_progressView setProgress:data.progress/data.zipSize];
    
}

- (void)setDowloadSate:(int)state{
    switch (state) {
        case 1:{
            //下载完成
            _downloadBtn.hidden = YES;
            _progressLabel.textColor = [UIColor darkGrayColor];
            _progressLabel.text = [NSString stringWithFormat:@"%@ %.f%%",[[DataCenter instance] getStringForKey:@"DownloadComplete"],_scenic.progress/_scenic.zipSize*100];
        }
            break;
        case 2:{
            //正在下载
            _downloadBtn.hidden = NO;
            _progressLabel.textColor = THEMECOLOR;
            [_downloadBtn setTitle:[[DataCenter instance] getStringForKey:@"pause"] forState:UIControlStateNormal];
            _progressLabel.text = [NSString stringWithFormat:@"%@ %.f%%",[[DataCenter instance] getStringForKey:@"Downloading"],_scenic.progress/_scenic.zipSize*100];
        }
            
            break;
        case 3:{
            //暂停中
            _downloadBtn.hidden = NO;
            _progressLabel.textColor = [UIColor redColor];
            _progressLabel.text = [NSString stringWithFormat:@"%@ %.f%%",[[DataCenter instance] getStringForKey:@"paused"],_scenic.progress/_scenic.zipSize*100];
            [_downloadBtn setTitle:[[DataCenter instance] getStringForKey:@"continueDownload"] forState:UIControlStateNormal];
        }
            
            break;
        case 4:{
            //更新下载
            _downloadBtn.hidden = NO;
            _progressLabel.textColor = THEMECOLOR;
            [_downloadBtn setTitle:[[DataCenter instance] getStringForKey:@"update"] forState:UIControlStateNormal];
            _progressLabel.text = [NSString stringWithFormat:@"%@ %.f%%",[[DataCenter instance] getStringForKey:@"DownloadComplete"],_scenic.progress/_scenic.zipSize*100];
        }
            
            break;
        default:
            break;
    }
}

-(void)dealloc{
    @try {
        [_scenic removeObserver:self forKeyPath:@"progress"];
        [_scenic removeObserver:self forKeyPath:@"isDownloading"];
    }
    @catch (NSException *exception) {
        
    }
    @finally {
        
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"progress"]) {
        if (_scenic.progress == _scenic.zipSize){
            [self setDowloadSate:1];
        }else{
            [self setDowloadSate:2];

        }
        [_progressView setProgress:_scenic.progress/_scenic.zipSize];
    }else{
        if (_scenic.isDownloading) {
            [self setDowloadSate:2];
        }else{
            [self setDowloadSate:3];
        }
    }
}

-(void)cancelDownload:(id)sender{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[[DataCenter instance] getStringForKey:@"Tips"] message:[[DataCenter instance] getStringForKey:@"delete_tip"] delegate:self cancelButtonTitle:[[DataCenter instance] getStringForKey:@"Cancel"] otherButtonTitles:[[DataCenter instance] getStringForKey:@"Sure"], nil];
    [alert show];
}

-(void)download:(id)sender{
    if (_scenic.isDownloading) {
        [[DownloadManagement instance] pauseDownload:_scenic];
    }else{
        [[DownloadManagement instance] addTarget:_scenic];
    }
    
    if (_scenic.isDownloading) {
        [self setDowloadSate:2];
    }else{
        [self setDowloadSate:3];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [[DownloadManagement instance] deleteTarget:_scenic];
    }
}

@end
